﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;

namespace SharingCenter.Web.Classes.Account
{

    public enum AccountActivateResult
    {
        Success,
        AlreadyActivated,
        Fail,
        NotFound,
        InvalidCode
    }

    public static class AccountOperations
    {
        //public static bool UserSignedUp(Guid userId, Guid eventId)
        //{
        //    var q = from req in scDataContext.Instance.Sc_EventRequests
        //            where req.RequestorUserId == userId && (req.Status == EventRequestStatusEnum.Approved || req.Status == EventRequestStatusEnum.Pending)
        //                && req.EventId == eventId
        //            select req;
        //    return q.Count() == 1;
        //}

        ////public static void UpdateParticipantGender(Guid userId, Guid eventId)
        ////{
        ////    try
        ////    {
        ////        Sc_Event evt = scDataContext.Instance.Sc_Events.Single(d => (d.EventId == eventId && d.AdminApproved));
        ////        Sc_Profile p = scDataContext.Instance.Sc_Profiles.Single(d => d.UserId == userId);
        ////        if (p.Gender == SharingCenter.Web.Classes.enums.Gender.Male)
        ////        {
        ////            evt.MaleParticipants++;
        ////        }
        ////        else
        ////        {
        ////            evt.FemaleParticipants++;
        ////        }

        ////        scDataContext.Instance.SubmitChanges();
        ////    }
        ////    catch { }
        ////}

        //public static void SignUp(Guid userId, Guid eventId)
        //{
        //    Sc_EventRequest r = null;

        //    using (scDataContext cxt = new scDataContext())
        //    {
        //        Sc_Event a = cxt.Sc_Events.Single(d => d.EventId == eventId);
        //        EventRequestStatusEnum status = a.NeedApproval ? EventRequestStatusEnum.Pending : EventRequestStatusEnum.Approved;

        //        try
        //        {
        //            r = cxt.Sc_EventRequests.Single(d => (d.EventId == eventId && d.RequestorUserId == userId && (d.Status == EventRequestStatusEnum.Rejected || d.Status == EventRequestStatusEnum.Cancelled)));
        //            r.Status = status;
        //            r.StatusChangeDate = DateTime.Now;
        //            r.Comment += Environment.NewLine + "用户主动请求";
        //        }
        //        catch
        //        {
        //            r = new Sc_EventRequest();
        //            r.RequestId = Guid.NewGuid();
        //            r.EventId = eventId;
        //            r.RequestDate = DateTime.Now;
        //            r.Status = status;
        //            r.RequestorUserId = userId;
        //            r.StatusChangeDate = DateTime.Now;
        //            r.Comment = "用户主动请求";

        //            cxt.Sc_EventRequests.InsertOnSubmit(r);
        //        }

        //        if (!a.NeedApproval)
        //        {
        //            UpdateParticipantGender(userId, eventId);
        //        }

        //        cxt.SubmitChanges();
        //    }


        //}
        

        public static aspnet_User GetUser(string userName)
        {
            try
            {
                return scDataContext.Instance.aspnet_Users.Single(d => d.LoweredUserName == userName.ToLower());
            }
            catch
            {
                return null;
            }
        }

        public static string GenerateActivateCode(string userName)
        {
            return FormsAuthentication.HashPasswordForStoringInConfigFile(userName + DateTime.Now.ToString() + Guid.NewGuid(), "MD5");
        }

        public static AccountActivateResult ActivateUser(string userName, string activateCode, out MembershipUser u)
        {
            AccountActivateResult result = AccountActivateResult.Success;
            u = null;
            try
            {
                try
                {
                    u = Membership.GetUser(userName);
                    string[] args = u.Comment.Split(WebConsts.STR_SEPERATOR);
                    if (args[0] != activateCode)
                    {
                        result = AccountActivateResult.InvalidCode;
                    }
                    else if(u.IsApproved)
                    {
                        result = AccountActivateResult.AlreadyActivated;
                    }
                    else
                    {
                        u.IsApproved = true;
                        Membership.UpdateUser(u);
                    }
                }
                catch 
                {
                    result = AccountActivateResult.NotFound;
                }
            }
            catch
            {
                result = AccountActivateResult.Fail;
            }

            return result;
        }

        public static string GetUserNameByUserId(Guid userId)
        {
            //try
            //{
            //    var q = from u in scDataContext.Instance.aspnet_Users
            //            where u.UserId == userId
            //            select u.UserName;
            //    return q.First();
            //}
            //catch
            //{
            //    return string.Empty;
            //}

            return scDataContext.Instance.GetUserNameByUserId(userId);
        }

        public static void LockUser(Guid userId, string reason)
        {
            aspnet_Membership m = scDataContext.Instance.aspnet_Memberships.Single(d => d.UserId == userId);
            m.IsLockedOut = true;
            m.LastLockoutDate = DateTime.Now;
            scDataContext.Instance.SubmitChanges();
            //scDataContext.Instance.Refresh(System.Data.Linq.RefreshMode.OverwriteCurrentValues, m);
        }

        public static void UnlockUser(Guid userId)
        {
            MembershipUser m = Membership.GetUser(GetUserName(userId));
            m.UnlockUser();
        }

        public static string GetUserName(Guid userId)
        {
            return GetUserNameByUserId(userId);
        }

        public static void CancelAccount(Guid userId)
        {
            string username = GetUserName(userId);
            scDataContext.Instance.DeleteUser(userId);
            Membership.DeleteUser(username, true);
        }

        public static WebProfile GetWebProfile(Guid userId)
        {
            return WebProfile.GetProfile(GetUserName(userId));
        }

        public static bool IsUserOnline(Guid userId)
        {
            string userName = GetUserName(userId);
            MembershipUser u = Membership.GetUser(userName);
            return u.IsOnline;
        }


        //public static void CancelSignUp(Guid userId, Guid eventId)
        //{
        //    try
        //    {
        //        Sc_EventRequest r = scDataContext.Instance.Sc_EventRequests.Single(d => (d.EventId == eventId && d.RequestorUserId == userId));
        //        r.Status = EventRequestStatusEnum.Cancelled;
        //        r.StatusChangeDate = DateTime.Now;
        //        r.Comment = "用户主动取消";

        //        Sc_Profile p = scDataContext.Instance.Sc_Profiles.Single(d => d.UserId == userId);

        //        Sc_Event a = scDataContext.Instance.Sc_Events.Single(d => d.EventId == eventId);
        //        if (p.Gender == SharingCenter.Web.Classes.enums.Gender.Male)
        //        {
        //            if (a.MaleParticipants > 0)
        //                a.MaleParticipants -= 1;
        //        }
        //        else
        //        {
        //            if (a.FemaleParticipants > 0)
        //                a.FemaleParticipants -= 1;
        //        }

        //        scDataContext.Instance.SubmitChanges();
        //    }
        //    catch
        //    {
        //    }
        //}
    }
}
